//
//  JDUserBusinessNewsTypeController.swift
//  DragonWallet
//
//  Created by volantPig on 2024/8/13.
//

import UIKit

class JDUserBusinessNewsTypeController: JDBaseViewController {

    var typeList: [JDUserBusinessNewsTypeModel?]?
    
    var mainCollectionView: UICollectionView?
    
    var bottomContainerView: UIView?
    var cancelButton: UIButton?
    var confirmButton: UIButton?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.setupConfig()
        self.setUIElements()
        self.getNetData()
        // Do any additional setup after loading the view.
    }
    
    func setupConfig() {
        self.title = "商讯类型"
        self.setupLeftBackItem()
    }
    
    func setUIElements() {
        
        self.bottomContainerView = UIView()
        self.view.addSubview(self.bottomContainerView!)
        self.bottomContainerView?.snp.makeConstraints({ make in
            make.left.right.equalTo(self.view)
            make.bottom.equalTo(self.view)
            make.height.equalTo(104)
        })
        self.bottomContainerView?.backgroundColor = .white

        self.cancelButton = UIButton(type: .custom)
        self.bottomContainerView?.addSubview(self.cancelButton!)
        self.cancelButton?.snp.makeConstraints({ make in
            make.right.equalTo(self.bottomContainerView!.snp.centerX).offset(-5)
            make.centerY.equalTo(self.bottomContainerView!)
            make.left.equalTo(self.bottomContainerView!).offset(12)
            make.height.equalTo(54)
        })
        self.cancelButton?.layer.cornerRadius = 27
        self.cancelButton?.backgroundColor = color("#F5F6F8")
        self.cancelButton?.setTitle("返回", for: .normal)
        self.cancelButton?.titleLabel?.font = UIFont.systemFont(ofSize: 16, weight: .regular)
        self.cancelButton?.setTitleColor(.black, for: .normal)
        self.cancelButton?.addTarget(self, action: #selector(backAction), for: .touchUpInside)
        
        self.confirmButton = UIButton(type: .custom)
        self.bottomContainerView?.addSubview(self.confirmButton!)
        self.confirmButton?.snp.makeConstraints({ make in
            make.left.equalTo(self.bottomContainerView!.snp.centerX).offset(5)
            make.right.equalTo(self.bottomContainerView!).offset(-12)
            make.height.equalTo(54)
            make.centerY.equalTo(self.bottomContainerView!)
        })
        self.confirmButton?.setTitle("确定", for: .normal)
        self.confirmButton?.backgroundColor = color("#FA6161")
        self.confirmButton?.titleLabel?.font = UIFont.systemFont(ofSize: 16, weight: .regular)
        self.confirmButton?.setTitleColor(.white, for: .normal)
        self.confirmButton?.layer.cornerRadius = 27
        self.confirmButton?.addTarget(self, action: #selector(confirmAction), for: .touchUpInside)
        
        let layout = UICollectionViewFlowLayout()
        layout.scrollDirection = .vertical

        self.mainCollectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
        self.view.addSubview(self.mainCollectionView!)
        self.mainCollectionView?.snp.makeConstraints({ make in
            make.left.right.equalTo(self.view)
            make.top.equalTo(self.view).offset(12)
//            make.bottom.equalTo(self.view)
            make.bottom.equalTo(self.bottomContainerView!.snp.top).offset(-12)
        })
        self.mainCollectionView?.backgroundColor = .commonColor()
        self.mainCollectionView?.delegate = self
        self.mainCollectionView?.dataSource = self
        
        self.mainCollectionView?.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "myCell")
    }
    
    func getNetData() {
        JDNetWorkRequest(.listUserBusinessType) { responseStr in
            
            printLog("商讯类型信息:\(responseStr)")
            
            let commonModel = JDCommonModel.deserialize(from: responseStr, designatedPath: "")
            if commonModel?.code == "0" {
                if let models = [JDUserBusinessNewsTypeModel].deserialize(from: responseStr, designatedPath: "data") {
                    self.typeList = models
                }
//                {"msg":"ok","data":[{"businessCode":400,"businessName":"全部","selected":false}],"code":0}
            }
            self.mainCollectionView?.reloadData()
            
        } failure: { error in
            
        } error: { errorCode in
            
        }

    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */
    
    @objc func confirmAction() {
        
        var selectedCodeList = [String]()
        
        for typeModel in self.typeList ?? [JDUserBusinessNewsTypeModel]() {
            if typeModel?.selected ?? false {
                if let code = typeModel?.businessCode {
                    selectedCodeList.append(code)
                }
            }
        }
        
        if selectedCodeList.count <= 0 {
            self.view.toast(message: "请选择商讯类型")
            return
        }
        printLog("确认按钮,修改商讯类型:\(selectedCodeList)")
        
        var params = [String: Any]()
        params["businessCodeList"] = selectedCodeList
        
        JDNetWorkRequest(.saveUserBusinessType(params)) { responseStr in
            
            printLog("保存成功:\(responseStr)")
            
            let commonModel = JDCommonModel.deserialize(from: responseStr, designatedPath: "")
            if commonModel?.code == "0" {
                self.backAction()
            }
            
        } failure: { error in
            
        } error: { errorCode in
            
        }
        
    }

}

extension JDUserBusinessNewsTypeController: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.typeList?.count ?? 0
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "myCell", for: indexPath)
        
        for subV in cell.contentView.subviews {
            subV.removeFromSuperview()
        }
        cell.contentView.backgroundColor = .clear
        
        let currentModel = self.typeList?[indexPath.row]
        
        let typeLabel = UILabel()
        cell.contentView.addSubview(typeLabel)
        typeLabel.snp.makeConstraints { make in
            make.left.right.top.bottom.equalTo(cell.contentView)
        }
        typeLabel.text = currentModel?.businessName
        typeLabel.textAlignment = .center
        typeLabel.layer.cornerRadius = 8
        typeLabel.clipsToBounds = true
        
        
        if currentModel?.selected ?? false {
            typeLabel.backgroundColor = color("#FA6161")
            typeLabel.textColor = .white
        } else {
            typeLabel.backgroundColor = .white
            typeLabel.textColor = .black
        }
        
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
        return UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 10)
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
        return 10
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
        return 10
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSizeMake((screenWidth-40-0.01)/3.0, 58)
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        printLog("点击:\(indexPath.row)")
        let selectedModel = self.typeList?[indexPath.row]
        selectedModel?.selected = !(selectedModel?.selected ?? false)
        self.mainCollectionView?.reloadData()
    }
}
